<?php

namespace app\admin\controller\weixin;

use app\common\controller\Backend;
use addons\weixin\library\WechatService;

/**
 * 微信菜单  控制器
 * Class Menus
 * @package app\admin\controller\wechat
 */
class Menus extends Backend
{
    public function index()
    {
        $buttons = [];
        $error_msg = '';
        try {
            $buttons = WechatService::menuService()->current();
            $buttons = $buttons['selfmenu_info']['button'] ?? [];
        } catch (\Exception $e) {
            $error_msg = $e->getMessage();
        }
        $this->view->assign('menus', $buttons);
        $this->view->assign('error_msg', $error_msg);

        return $this->view->fetch();
    }

    /**
     * 同步
     */
    public function sync()
    {
        $buttons = $this->request->post("menu");
        $buttons = (array)json_decode($buttons, true);
        try {
            $menu = WechatService::menuService();
            $menu->delete(); // 删除全部菜单
            if (!empty($buttons)) {
                $res = $menu->create($buttons); //重新创建菜单
                if (isset($res['errcode']) && $res['errcode'] != 0) {
                    throw new \Exception($res['errmsg']);
                }
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('同步成功!');
    }
}
